package com.hliushi.demo.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.TimeZone;

/**
 * 编写一个类用来保存springboot应用上下文对象的引用,
 * 此类也可以用来在非spring管理类下获取SpringBean
 *
 * @author llhuang10
 * @date 2021/7/22 9:10
 */
public class SpringUtil {

    private static ApplicationContext applicationContext;

    /**
     * 0-2 表示开发, 测试, 生成环境
     */
    private static byte environ = 0;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 保存上下文对象的同时拿到我们激活的配置文件后缀名
     *
     * @param context
     */
    public static void setApplicationContext(ApplicationContext context) {
        SpringUtil.applicationContext = context;

        // 获取当前的系统环境
        Environment env = applicationContext.getEnvironment();

        String[] activeProfiles = env.getActiveProfiles();
        for (String profile : activeProfiles) {
            if ("dev".equals(profile)) {
                break;
            } else if ("test".equals(profile)) {
                environ = 1;
                break;
            } else if ("prod".equals(profile)) {
                environ = 2;
                break;
            }
        }
        callbackAfterRunning();
    }


    /**
     * 获取配置文件配置值
     *
     * @param key
     * @return
     */
    public static String getEvnProperty(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }

    /**
     * 通过bean名称获取bean
     *
     * @param name
     * @return
     */
    public static Object getBeanByName(String name) {
        try {
            return getApplicationContext().getBean(name);
        } catch (BeansException e) {
            return null;
        }
    }

    public static Object getBeanByClassName(String className) {
        try {
            Class<?> forName = Class.forName(className);
            return getApplicationContext().getBean(forName);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        if (SpringUtil.applicationContext == null) {
            return null;
        }
        try {
            return SpringUtil.applicationContext.getBean(clazz);
        } catch (Exception e) {
            return null;
        }
    }

    //当前是否为开发环境
    public static boolean isDev() {
        return environ == 0;
    }

    //是否为测试环境
    public static boolean isTest() {
        return environ == 1;
    }

    //是否为生产环境
    public static boolean isProd() {
        return environ == 2;
    }

    // 获取当前环境
    public static byte getEnviron() {
        return environ;
    }

    private static void callbackAfterRunning() {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
    }

}
